package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JieGunGateway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(JieGunGateway.class);

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = "";
        try {
            String params = buildParam(entity);
            String password = MD5Util.encode(MD5Util.encode(replace(params)).toLowerCase() + info.getPassword()).toLowerCase();
            String url = info.getServerAddr() + "?mac=" + password;
            logger.info("params : {}, password : {}", params, password);
            String response = doPost(url, params);
            if (response == null) {
                result = "网关请求超时";
                return;
            }
            logger.info("JieGunGateway send url : {}, params : {}, result : {}", url, params, response);
            Map map = JSON.parseObject(response, Map.class);
            Map body = (Map) map.get("body");
            String code = body.get("result").toString();
            if ("0000".equals(code)) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
                result = body.get("reason").toString();
            } else {
                result = code + ":" + body.get("reason");
            }
        } catch (Exception e) {
            logger.error("JieGunGateway error ! ", e);
        } finally {
            onSubmitResponse(status, entity.getMessageId(), result);
        }
    }

    public static String replace(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        System.out.print(l + "======" + l % 100000000000L);
    }

    private String buildParam(SendQueueEntity entity) {
        Map<String, Object> root = new HashMap<>();
        Map<String, String> header = new HashMap<>();
        Map<String, String> body = new HashMap<>();
        header.put("serviceName", "IVRRequest");
        header.put("messageId", entity.getMessageId());
        header.put("vccId", info.getAccount());
        body.put("displayNum", info.getAccessNumber());
        body.put("calledNum", entity.getPhone());
        body.put("bussinessId", "0000001");
        body.put("serviceKey", "900008");
        body.put("playMode", "3");
        body.put("mediaContent", entity.getContent());
        body.put("playTime", "2");
        root.put("header", header);
        root.put("body", body);
        return JSON.toJSONString(root);
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        try {
            String param = entity.getParam();
            logger.info("JieGunGateway notifyStatus param : {}", param);
            Map paramMap = JSON.parseObject(param, Map.class);
            int status = SmsMsgStatusEnum.SEND_FAIL.index;
            Map body = (Map) paramMap.get("body");
            Map header = (Map) paramMap.get("header");
            int calledDuration = Integer.valueOf(body.get("calledDuration").toString());
            int duration = Integer.valueOf(body.get("duration").toString());
            //两个字段大于0  都是计费的   等于0或者小于0不计费
            if (calledDuration > 0 && duration > 0) {
                status = SmsMsgStatusEnum.SEND_SUCCESS.index;
            }
            String messageId = header.get("messageId").toString();
            String result = body.get("callId").toString();
            if (StringUtils.isBlank(messageId)) {
                logger.warn("JieGunGateway notifyStatus messageId is null params : {}", param);
            }
            receiveReport(status, messageId, result);
            return true;
        } catch (Exception e) {
            logger.error("JieGunGateway notifyStatus error ! ", e);
            return false;
        }
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return true;
    }

    @Override
    public int queryBalance() throws Exception {
        return 0;
    }
}
